const router = require('koa-router')()
const crypto = require('crypto')
const path = require('path');

const name = path.basename(__filename, path.extname(__filename));
router.prefix(`/${name}`)


const appid = '20240813002122517'
const securityKey = 'R1VWv5aTRNehd4bHIDE9'


router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 22222!'
  })
})

router.post('/translate', (req, res) => {
  const q = req.body.q // 要翻译的文本
  const from = req.body.from // 源语言
  const to = req.body.to // 目标语言

  if (!q || !from || !to) {
      return res.status(400).send('Missing required parameters.')
  }

  const salt = new Date().getTime() // 当前时间戳作为salt
  const sign = crypto.createHash('md5').update(`${appid}${q}${salt}${securityKey}`).digest('hex')

  const options = {
      q,
      from,
      to,
      appid,
      salt,
      sign
  }

  const url = `https://fanyi-api.baidu.com/api/trans/vip/translate?${new URLSearchParams(options)}`

  fetch(url)
      .then(response => response.json())
      .then(data => {
          if (data.error_code) {
              return res.status(500).send(`Translation error: ${data.error_msg}`)
          }
          res.send(data)
      })
      .catch(error => {
          console.error('Error fetching translation:', error)
          res.status(500).send('An error occurred while fetching the translation.')
      })
})

module.exports = router
